package database

import (
	KptLogger "gitee.com/xuyiping_admin/pkg/logger/logrus"
	"gitee.com/xuyiping_admin/pkg/xerr"
	"kpt-tmr-group/config"
	"time"

	"gorm.io/gorm"

	"gorm.io/driver/mysql"

	"gorm.io/gorm/logger"
)

type goRmLog struct {
}

func (g goRmLog) Printf(s string, i ...interface{}) {
	KptLogger.Infof(s, i...)

}

// NewDatabase return xorm engine
// with some default params
func NewDatabase(cfg *config.AppConfig, drivers ...string) (*gorm.DB, error) {

	newLogger := logger.New(
		goRmLog{},
		logger.Config{
			SlowThreshold: 5 * time.Second,
			LogLevel:      logger.Info,
		},
	)

	db, err := gorm.Open(mysql.New(mysql.Config{
		DriverName: cfg.StoreSetting.DriverName,
		DSN:        cfg.StoreSetting.KptEventDSNRW}),
		&gorm.Config{Logger: newLogger},
	)
	if err != nil {
		panic(xerr.WithStack(err))
	}

	if cfg.StoreSetting.ShowSQL {
		db.Logger.LogMode(logger.Info)
	}

	return db, err
}
